import { Component,ViewChild,ElementRef,ChangeDetectorRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

//网络请求
import { ConfigProvider } from '../../providers/config/config';
import { HttpserviesProvider } from '../../providers/httpservies/httpservies';
import { Http,Jsonp } from '@angular/http';
import { StorageProvider } from '../../providers/storage/storage';

import { CartPage } from '../cart/cart';

/**
 * Generated class for the GoodsdetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 * 
 * 操作DOM节点选择商品属性
 * 1.获取DOM节点，操作DOM节点
 */

@IonicPage()
@Component({
  selector: 'page-goodsdetail',
  templateUrl: 'goodsdetail.html',
})
export class GoodsdetailPage {

  @ViewChild('myAttr') myattr:ElementRef

  public tabs = 'plist';
  public item = [];
  public num = 1; //默认商品的件数为1
  public carts_num = 0; //加入购物车的数量， 默认为0
  public CartPage = CartPage;

  constructor(
     public navCtrl: NavController,
     public navParams: NavParams, 
     public config:ConfigProvider, 
     public httpService:HttpserviesProvider,
     public storage:StorageProvider,
     public changeRef:ChangeDetectorRef,
    ) {
    
    this.requestGoodDetailData();
    this.carts_num = this.getProductNumData();

  }

  //视图加载完毕调用， 只会加载一次
  ionViewDidLoad() {
    this.bindEvent();
  }

  //请求商品详情
  requestGoodDetailData(){
    //http://39.108.159.135/api/pcontent?id=59f6a2d27ac40b223cfdcf81
    var url = 'api/pcontent?id='+this.navParams.data.id;
    this.httpService.requestData(url,(data)=>{
      console.log(data.result);
      this.item = data.result;
    });
  }

  //绑定事件的方法
  //利用原生的javaScript的DOM节点操作实现商品属性的选择
  bindEvent(){
    console.log(this.myattr.nativeElement);
    var attrDom=this.myattr.nativeElement;
    attrDom.onclick=function(e){
        // console.log(e.srcElement.nodeName);  //元素名称
        // console.log(e.target);  //DOM节点
        // console.log(e.target.parentNode.parentNode);

        var curDom = e.target.parentNode.parentNode;
        if(curDom.nodeName=='SPAN'){
            var ele:any=e.target.parentNode.parentNode;   /*获取点击的元素注意*/
            var parentNode=ele.parentNode;  /*获取当前元素的父节点*/
            var children=parentNode.children;   /*获取父节点下面的所有子节点  去掉空白节点*/
            for(var i=0;i<children.length;i++){
              children[i].className='';
            }
            ele.className='active';
        }
    }
  }

  //加入购物车
  addCart(){
    //获取商品的数据
    var product_title = this.item['title'];
    var product_id=this.item['_id'];
    var product_pic=this.item['pic'];
    var product_price=this.item['price'];
    var product_count=this.num;  /*商品数量*/
    var checked = true;
    //商品的属性
    var product_attr = '';
    //es5 获取dom节点的方式
    var activeDom=document.querySelectorAll('#myattr .active');
    // var attrDom = document.getElementById('myattr');
    // var activeDom = attrDom.getElementsByClassName('.active');
    console.log(activeDom);
    for(var i=0; i<activeDom.length; i++){
      var activeHTML:any = activeDom[i];
      product_attr+=activeHTML.innerText;
    }
    console.log(product_attr);

    //商品的属性数据
    var json = {
      'product_title':product_title,
      'product_id':product_id,
      product_pic,
      product_price,
      product_count,
      product_attr,
      checked,
    }
    // console.log(json);

    //加入购物车的数据保存到localStorage,方便在购物车页面获取之前加入购物车的数据
    this.productDataToLocalStorage(json,product_id);
  }

  productDataToLocalStorage(json,product_id){
    var storageData = this.storage.get('carts_data');
    if(storageData){//本地有数据
      //判断购物车中有没有当前这条数据
      if(this.hasProductData(storageData,json.product_id)){//有当前这条数据，数量+1，
        for(var j=0; j<storageData.length;j++){
          var tmpJson = storageData[j];
          if(tmpJson.product_id==product_id){
            tmpJson.product_count+=this.num; //当前这条商品的数量+1
          }
        }
      }else{//没有当前这条数据，
        storageData.push(json);
      }
      this.storage.set('carts_data',storageData);
    }else{//没有数据， 直接将选择的商品push到storage中
      var tempArr = [];
      tempArr.push(json);
      this.storage.set('carts_data',tempArr);
    }
    // console.log(storageData);
    this.carts_num = this.getProductNumData();
    // console.log(this.carts_num);
    
  }

  //判断是否存在当前这条数据
  hasProductData(storageData,product_id){
    if(storageData){
      for(var i=0;i<storageData.length;i++){
        if(storageData[i].product_id==product_id){
          return true;
        }
      }
    }
    return false;
  }

  //计算加入购物车的数量（右上角的商品数）
  getProductNumData(){
    var product_num = 0;
    var storageData = this.storage.get('carts_data');
    if(storageData){
      for(var i=0;i<storageData.length;i++){
        product_num+=storageData[i].product_count;
      }
    }
    return product_num;
  }

  //加
  addNum(){
    this.num+=1;
  }

  //减
  delNum(){
    if(this.num>1){
      this.num-=1;
    }
  }

}
